/**
 * 
 */
package com.ws.framework.remoteservice.core.consumer;

import java.util.Map;

import com.google.common.collect.Maps;
import com.ws.framework.remoteservice.core.model.ServiceKey;
import com.ws.framework.remoteservice.core.util.WrsiConstants;

/**
 * @author WSH
 *
 */
public class ServiceLocator {

	private final static boolean defaultLazyInit = false;
	
	private static final Map<ServiceKey, ServiceAgent> agents = Maps.newHashMap();

	public static <T> T getService(Class<?> constract) {
		return getService(constract, defaultLazyInit);
	}
	
	public static <T> T getService(Class<?> constract, String implCode) {
		return getService(constract, implCode, defaultLazyInit);
	}
	
	public static <T> T getService(Class<?> constract, boolean lazyInit) {
		return getService(constract, WrsiConstants.registry_for_default_provider, lazyInit);
	}
	
	public static <T> T getService(Class<?> constract, String implCode, boolean lazyInit) {
		return getService(constract.getName(), implCode, lazyInit);
	}
	
	public static ServiceAgent getServiceAgent(Class<?> constract) {
		return getServiceAgent(constract, WrsiConstants.registry_for_default_provider, defaultLazyInit);
	}
	
	public static ServiceAgent getServiceAgent(Class<?> constract, String implCode) {
		return getServiceAgent(constract, implCode, defaultLazyInit);
	}
	
	public static ServiceAgent getServiceAgent(Class<?> constract,  boolean lazyInit) {
		return getServiceAgent(constract, WrsiConstants.registry_for_default_provider, lazyInit);
	}
	
	public static ServiceAgent getServiceAgent(Class<?> constract, String implCode,  boolean lazyInit) {
		return getServiceAgent(constract.getName(), implCode, lazyInit);
	}

	private static ServiceAgent getServiceAgent(String constractName, String implCode, boolean lazyInit) {
		ServiceKey key = new ServiceKey(constractName, implCode);
		ServiceAgent agent = agents.get(key);
		if (agent != null) {
			return agent;
		}
		synchronized (agents) {
			agent = (ServiceAgent) agents.get(key);
			if (agent == null) {
				agent = new ServiceAgentImpl(key, lazyInit);
				agents.put(key, agent);
			}
		}
		return agent;
	}

	@SuppressWarnings("unchecked")
	private static <T> T getService(String constractName, String implCode, boolean lazyInit) {
		Object object = new JdkProxyFactory().getProxy(getServiceAgent(constractName, implCode, lazyInit));
		return (T) object;
	}

}
